
package com.epam.android.training.day8.task2;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

/**
 * Asyncronous task for factorial calculation
 * 
 * @author Anton Novikov
 */
public class AsyncFactorialCalculator extends AsyncTask<Integer, Void, Integer> {

  private final Handler progressHandler;

  /**
   * Creates an instance of AsyncFactorialCalculator.
   */
  public AsyncFactorialCalculator(Handler progressHandler) {
    this.progressHandler = progressHandler;
  }

  @Override
  protected Integer doInBackground(Integer... params) {

    if (params.length != 1) {
      throw new IllegalArgumentException("Task supports only one input parameter");
    }

    return factorial(params[0]);
  }

  @Override
  protected void onPostExecute(Integer result) {
    Message msg = Message.obtain();

    // send status finished to handeler.
    msg.obj = Status.FINISHED;
    // wait 3 seconds before finish async task.
    progressHandler.sendMessageDelayed(msg, 3000);
  }

  /**
   * Recurcive factorial calculation function.
   * 
   * @param source number to calculate factorial for
   * @return factorial of source number
   */
  private int factorial(int source) {
    if (source < 0) {
      throw new IllegalArgumentException("Factorial can be calculated only for positieves.");
    }

    return source != 0 ? source * factorial(source - 1) : 1;
  }
}
